from django.contrib.auth import get_user_model
from rest_framework.request import Request
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions

from users.models import User
from drf_shop_admin.utils.jwt_util import JwtUtil


class JwtAuthentication(BaseAuthentication):
    """自定义的Jwt认证"""
    def authenticate(self, request: Request):
        token = request._request.headers.get('Authentication', None)
        if token is None:
            raise exceptions.AuthenticationFailed('用户未登录')

        try:
            payload = JwtUtil.check_jwt_token(token)
        except Exception:
            msg = '认证失败，token过期'
            raise exceptions.AuthenticationFailed(msg)

        user = self.authenticate_credentials(payload)
        # print(user)
        return (user, token)

    def authenticate_credentials(self, payload):
        """
        Returns an active user that matches the payload's user id and email.
        """
        user = User.objects.all().filter(id=payload.get('id')).first()

        if not user:
            msg = '用户不存在.'
            raise exceptions.AuthenticationFailed(msg)

        return user

    def authenticate_header(self, request):
        pass